#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
云盘客户端工厂类
根据云盘类型创建对应的客户端实例
"""

from typing import Optional, Dict, Any
from .base_client import BaseCloudClient

class CloudFactory:
    """云盘客户端工厂类"""
    
    # 支持的云盘类型
    SUPPORTED_TYPES = {
        'tianyi': '天翼云盘',
        'baidu': '百度网盘',
        'aliyun': '阿里云盘',
        'onedrive': 'OneDrive',
        'googledrive': 'Google Drive'
    }
    
    @classmethod
    def create_client_for_login(cls, cloud_type: str, account_id: int, username: str, 
                               password: str, enable_debug: bool = False) -> Optional[BaseCloudClient]:
        """
        创建用于登录的云盘客户端（使用账号密码）
        
        Args:
            cloud_type: 云盘类型 (tianyi, baidu, aliyun, onedrive, googledrive)
            account_id: 云存储账号ID
            username: 用户名
            password: 密码
            enable_debug: 是否启用调试模式
            
        Returns:
            BaseCloudClient: 云盘客户端实例，失败返回None
        """
        import logging
        logger = logging.getLogger('CloudFactory')
        logger.info(f"开始创建云盘客户端: 类型={cloud_type}, 账号ID={account_id}, 用户名={username}")
        
        cloud_type = cloud_type.lower()
        
        if cloud_type not in cls.SUPPORTED_TYPES:
            error_msg = f"不支持的云盘类型: {cloud_type}。支持的类型: {list(cls.SUPPORTED_TYPES.keys())}"
            logger.error(error_msg)
            raise ValueError(error_msg)
        
        try:
            if cloud_type == 'tianyi':
                logger.info("正在导入天翼云盘客户端...")
                from .tianyi import Cloud189Client
                logger.info("天翼云盘客户端导入成功，正在创建登录实例...")
                client = Cloud189Client(account_id, username, password, enable_debug)
                logger.info("天翼云盘登录客户端创建成功")
                return client
            elif cloud_type == 'baidu':
                from .baidu import BaiduClient
                client = BaiduClient(account_id, username, password, enable_debug)
                return client
            elif cloud_type == 'aliyun':
                from .aliyun import AliyunClient
                client = AliyunClient(account_id, username, password, enable_debug)
                return client
            elif cloud_type == 'onedrive':
                from .onedrive import OneDriveClient
                client = OneDriveClient(account_id, username, password, enable_debug)
                return client
            elif cloud_type == 'googledrive':
                # TODO: 实现Google Drive客户端
                raise NotImplementedError("Google Drive客户端尚未实现")
        except ImportError as e:
            error_msg = f"无法导入{cls.SUPPORTED_TYPES[cloud_type]}客户端: {e}"
            logger.error(error_msg, exc_info=True)
            raise ImportError(error_msg)
        except Exception as e:
            error_msg = f"创建{cls.SUPPORTED_TYPES[cloud_type]}客户端失败: {e}"
            logger.error(error_msg, exc_info=True)
            raise Exception(error_msg)
        
        return None
    
    @classmethod
    def create_client_with_token(cls, cloud_type: str, account_id: int, username: str, 
                                token_info: Dict[str, Any], enable_debug: bool = False) -> Optional[BaseCloudClient]:
        """
        创建使用token的云盘客户端（用于检测和文件操作）
        
        Args:
            cloud_type: 云盘类型 (tianyi, baidu, aliyun, onedrive, googledrive)
            account_id: 云存储账号ID
            username: 用户名
            token_info: token信息，用于恢复登录状态
            enable_debug: 是否启用调试模式
            
        Returns:
            BaseCloudClient: 云盘客户端实例，失败返回None
        """
        import logging
        logger = logging.getLogger('CloudFactory')
        logger.info(f"开始创建使用token的云盘客户端: 类型={cloud_type}, 账号ID={account_id}, 用户名={username}")
        
        cloud_type = cloud_type.lower()
        
        if cloud_type not in cls.SUPPORTED_TYPES:
            error_msg = f"不支持的云盘类型: {cloud_type}。支持的类型: {list(cls.SUPPORTED_TYPES.keys())}"
            logger.error(error_msg)
            raise ValueError(error_msg)
        
        try:
            if cloud_type == 'tianyi':
                logger.info("正在导入天翼云盘客户端...")
                from .tianyi import Cloud189Client
                logger.info("天翼云盘客户端导入成功，正在创建token实例...")
                # 创建客户端时不需要密码，因为使用token
                client = Cloud189Client(account_id, username, None, enable_debug)
                # 设置token信息到客户端
                logger.info("设置token信息到客户端...")
                client.set_token_info(token_info)
                logger.info("天翼云盘token客户端创建成功")
                return client
            elif cloud_type == 'baidu':
                from .baidu import BaiduClient
                client = BaiduClient(account_id, username, None, enable_debug)
                client.set_token_info(token_info)
                return client
            elif cloud_type == 'aliyun':
                from .aliyun import AliyunClient
                client = AliyunClient(account_id, username, None, enable_debug)
                client.set_token_info(token_info)
                return client
            elif cloud_type == 'onedrive':
                from .onedrive import OneDriveClient
                client = OneDriveClient(account_id, username, None, enable_debug)
                client.set_token_info(token_info)
                return client
            elif cloud_type == 'googledrive':
                # TODO: 实现Google Drive客户端
                raise NotImplementedError("Google Drive客户端尚未实现")
        except ImportError as e:
            error_msg = f"无法导入{cls.SUPPORTED_TYPES[cloud_type]}客户端: {e}"
            logger.error(error_msg, exc_info=True)
            raise ImportError(error_msg)
        except Exception as e:
            error_msg = f"创建{cls.SUPPORTED_TYPES[cloud_type]}客户端失败: {e}"
            logger.error(error_msg, exc_info=True)
            raise Exception(error_msg)
        
        return None
    
    @classmethod
    def create_client(cls, cloud_type: str, account_id: int, username: str, 
                     password: str, enable_debug: bool = False, token_info: Optional[Dict[str, Any]] = None) -> Optional[BaseCloudClient]:
        """
        创建云盘客户端（兼容性方法，推荐使用具体的create_client_for_login或create_client_with_token）
        
        Args:
            cloud_type: 云盘类型 (tianyi, baidu, aliyun, onedrive, googledrive)
            account_id: 云存储账号ID
            username: 用户名
            password: 密码
            enable_debug: 是否启用调试模式
            token_info: 可选的token信息，用于恢复登录状态
            
        Returns:
            BaseCloudClient: 云盘客户端实例，失败返回None
        """
        import logging
        logger = logging.getLogger('CloudFactory')
        logger.info(f"开始创建云盘客户端: 类型={cloud_type}, 账号ID={account_id}, 用户名={username}")
        
        cloud_type = cloud_type.lower()
        
        if cloud_type not in cls.SUPPORTED_TYPES:
            error_msg = f"不支持的云盘类型: {cloud_type}。支持的类型: {list(cls.SUPPORTED_TYPES.keys())}"
            logger.error(error_msg)
            raise ValueError(error_msg)
        
        try:
            if cloud_type == 'tianyi':
                logger.info("正在导入天翼云盘客户端...")
                from .tianyi import Cloud189Client
                logger.info("天翼云盘客户端导入成功，正在创建实例...")
                client = Cloud189Client(account_id, username, password, enable_debug)
                # 如果提供了token信息，设置到客户端
                if token_info:
                    logger.info("设置token信息到客户端...")
                    client.set_token_info(token_info)
                logger.info("天翼云盘客户端创建成功")
                return client
            elif cloud_type == 'baidu':
                from .baidu import BaiduClient
                client = BaiduClient(account_id, username, password, enable_debug)
                if token_info:
                    client.set_token_info(token_info)
                return client
            elif cloud_type == 'aliyun':
                from .aliyun import AliyunClient
                client = AliyunClient(account_id, username, password, enable_debug)
                if token_info:
                    client.set_token_info(token_info)
                return client
            elif cloud_type == 'onedrive':
                from .onedrive import OneDriveClient
                client = OneDriveClient(account_id, username, password, enable_debug)
                if token_info:
                    client.set_token_info(token_info)
                return client
            elif cloud_type == 'googledrive':
                # TODO: 实现Google Drive客户端
                raise NotImplementedError("Google Drive客户端尚未实现")
        except ImportError as e:
            error_msg = f"无法导入{cls.SUPPORTED_TYPES[cloud_type]}客户端: {e}"
            logger.error(error_msg, exc_info=True)
            raise ImportError(error_msg)
        except Exception as e:
            error_msg = f"创建{cls.SUPPORTED_TYPES[cloud_type]}客户端失败: {e}"
            logger.error(error_msg, exc_info=True)
            raise Exception(error_msg)
        
        return None
    
    @classmethod
    def get_supported_types(cls) -> Dict[str, str]:
        """
        获取支持的云盘类型
        
        Returns:
            Dict[str, str]: 云盘类型映射
        """
        return cls.SUPPORTED_TYPES.copy()
    
    @classmethod
    def is_supported(cls, cloud_type: str) -> bool:
        """
        检查是否支持指定的云盘类型
        
        Args:
            cloud_type: 云盘类型
            
        Returns:
            bool: 是否支持
        """
        return cloud_type.lower() in cls.SUPPORTED_TYPES
    
    @classmethod
    def get_type_name(cls, cloud_type: str) -> str:
        """
        获取云盘类型的中文名称
        
        Args:
            cloud_type: 云盘类型
            
        Returns:
            str: 中文名称
        """
        return cls.SUPPORTED_TYPES.get(cloud_type.lower(), '未知类型')